package com.jlastu.androidsx.model;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.jlastu.androidsx.bean.Merchant;
import com.jlastu.androidsx.bean.User;
import com.jlastu.androidsx.dao.MerchantDao;
import com.jlastu.androidsx.dao.UserDao;
import com.jlastu.androidsx.database.GreenDaoManager;

import java.util.List;

public class LoginViewModel extends AndroidViewModel {

    private Context mContext;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        this.mContext = application;
    }

    /**
     * 用户登录方法
     * @param name 用户名
     * @param password 密码
     * @param listener 登录监听器
     */
    public void userLogin(String name, String password, IUserLoginListener listener) {

        UserDao userDao = GreenDaoManager.getmInstance().getDaoSession().getUserDao();
        List<User> userList = userDao.loadAll();

        if (userList ==null || userList.size() ==0){
            listener.userLoginFail("账号或者密码错误");
            return;
        }
        for (int i = 0; i < userList.size(); i++) {
            if (name.equals(userList.get(i).getName()) && password.equals(userList.get(i).getPassword())){
                // 调用监听器的userLoginSuccess方法，将查询到的用户信息传递给监听器
                listener.userLoginSuccess(userList.get(i));
                return;
            }
        }
        listener.userLoginFail("账号或者密码错误");
    }

    /**
     * 商家登录方法
     * @param name 用户名
     * @param password 密码
     * @param listener 商家登录监听器
     */
    public void merchantLogin(String name, String password, IMerchantListener listener) {
        MerchantDao merchantDao = GreenDaoManager.getmInstance().getDaoSession().getMerchantDao();
        List<Merchant> merchantList = merchantDao.loadAll();
        // 如果监听器为空，则登录失败，返回未知错误
        if (listener == null) {
            listener.merchantLoginFail("未知错误");
            return;
        }


        if (merchantList ==null || merchantList.size() ==0){
            listener.merchantLoginFail("账号或者密码错误");
            return;
        }
        for (int i = 0; i < merchantList.size(); i++) {
            if (name.equals(merchantList.get(i).getUsername()) && password.equals(merchantList.get(i).getPassword())){
                // 调用监听器的userLoginSuccess方法，将查询到的用户信息传递给监听器
                listener.merchantLoginSuccess(merchantList.get(i));
                return;
            }
        }
        listener.merchantLoginFail("账号或者密码错误");
    }
}
